from contextlib import asynccontextmanager
from typing import AsyncGenerator, Callable, Any

from fastapi import Request
from sqlalchemy.exc import SQLAlchemyError, OperationalError
from sqlalchemy.ext.asyncio import AsyncSession




async def get_async_session_depends(request: Request) -> AsyncSession:
    """
    使用方法方式定义依赖项
    :param request: current request.
    :return: pyee_events producer from the core_app.
    """
    async with request.app.async_session_maker() as session:
        # await async_session.commit()
        try:
            yield session
            # 使用自动提交在某些情况下 会突发的asyncio.exceptions.CancelledError异常
            # await async_session.commit()
        except SQLAlchemyError as ex:
            print(ex)
            await session.rollback()

        finally:
            # 1.4.0版本的话 需要收的执行关闭，才可以 不然会一直超时
            # 1.4.19的话 这个地方可以起到关闭的作用！
            await session.close()




from afast_core.core_plugins.globalrequest.request import request


@asynccontextmanager
async def get_async_session_context() -> AsyncGenerator:
    async_session = request.app.async_session_maker()
    try:
        yield async_session
        # Exception during reset or similar
        # Traceback (most recent call last):
        # 使用自动提交在某些情况下 会突发的asyncio.exceptions.CancelledError异常
        # await async_session.commit()
    except OperationalError as ex:
        pass
        raise ex
    except SQLAlchemyError as ex:
        await async_session.rollback()
        raise ex
    finally:
        await async_session.close()



# async def execute_query(func: Callable[[AsyncSession], Any]):
#     async with global_async_session() as session:
#         try:
#             res = await func(session)
#             return res
#         except Exception as ex:
#             logger.exception(ex)
#             raise


def get_async_session_maker():
    try:
        return request.app.async_session_maker()
    except LookupError:
        pass
